package com.SouthernWall_404.Age_Capitalism.Client.Render;

import com.SouthernWall_404.Age_Capitalism.Client.Data.CachedEdge;
import com.SouthernWall_404.Age_Capitalism.Client.Render.RenderType.GlowRenderType;
import com.SouthernWall_404.Age_Capitalism.common.Init.ModItems;
import com.SouthernWall_404.Age_Capitalism.common.World.Entity.StoreBlockEntity;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.blaze3d.vertex.VertexFormat;
import com.mojang.math.Axis;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
import net.minecraft.client.renderer.block.ModelBlockRenderer;
import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.resources.model.BakedModel;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.trading.MerchantOffers;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.model.data.ModelDataManager;
import org.joml.Matrix4f;
import org.joml.Quaternionf;


public class HighlightBlockEntityRenderer implements BlockEntityRenderer<StoreBlockEntity> {

    private int degree = 0;
    private final ModelBlockRenderer blockModelRenderer;

    // 发光效果参数
    private static final float OUTLINE_THICKNESS = 0.02f; // 轮廓线厚度
    private static final float GLOW_INTENSITY = 1.5f;    // 发光强度
    private static final float[] OUTLINE_COLOR = {0.0f, 1.0f, 0.0f, 0.8f}; // 绿色半透明

    // 自定义渲染类型 - 解决顶点格式问题


    public HighlightBlockEntityRenderer(BlockEntityRendererProvider.Context context) {
        super();
        this.blockModelRenderer = context.getBlockRenderDispatcher().getModelRenderer();

    }


    @Override
    public void render(StoreBlockEntity blockEntity, float partialTick,
                       PoseStack poseStack, MultiBufferSource buffer,
                       int packedLight, int packedOverlay) {

//        this.renderModel(blockEntity, partialTick, poseStack, buffer, packedLight, packedOverlay);

        MerchantOffers merchantOffers = blockEntity.getOffers();
        if (!merchantOffers.isEmpty()) {
            this.renderItem(blockEntity, partialTick, poseStack, buffer, packedLight, packedOverlay);
        }


        if(blockEntity.isHighlighted())
        {
            this.renderHighLight(blockEntity, partialTick, poseStack, buffer, packedLight, packedOverlay);
        }
    }

    private void  renderModel(StoreBlockEntity blockEntity, float partialTick,
                              PoseStack poseStack, MultiBufferSource buffer,
                              int packedLight, int packedOverlay)
    {
        BlockState state = blockEntity.getBlockState();
        BlockRenderDispatcher blockRenderDispatcher=Minecraft.getInstance().getBlockRenderer();
        // 1. 获取模型
        BakedModel model = blockRenderDispatcher.getBlockModel(state);

        // 2. 准备渲染
        poseStack.pushPose();

        // 3. 应用变换（不需要旋转，原版ChestBlock已处理）
        // 只需调整位置
        poseStack.translate(0.5, 0.5, 0.5);
        poseStack.translate(-0.5, -0.5, -0.5);

        // 4. 渲染模型
        blockRenderDispatcher.getModelRenderer().renderModel(
                poseStack.last(),
                buffer.getBuffer(RenderType.entityCutout(TextureAtlas.LOCATION_BLOCKS)),
                state,
                model,
                1.0f, 1.0f, 1.0f,
                LightTexture.FULL_BRIGHT,
                packedOverlay,
                ModelData.EMPTY,
                null
        );

        poseStack.popPose();





    }

    private void renderItem(StoreBlockEntity blockEntity, float partialTick,
                            PoseStack poseStack, MultiBufferSource buffer,
                            int packedLight, int packedOverlay) {

        if (degree >= 360) {
            degree = 0;
        }

        poseStack.pushPose();//{[1,0,0][0,1,0][0,0,1]}[0,0,0]

        BlockState blockState=blockEntity.getBlockState();
        applyBlockStateRotation(blockState, poseStack);

//        poseStack.mulPose(new Quaternionf().rotateX((float) Math.PI/2));//{[1,0,0] ,[0,0,1],[0,-1,0]}
        poseStack.scale(1.5f,1.5f,1.5f);//{[1.5,0,0] ,[0,1.5,0],[0,0,1.5]}




        ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer();
        MerchantOffers merchantOffers = blockEntity.getOffers();
        ItemStack itemStack= new ItemStack(blockEntity.getOffers().get(0).getResult().getItem(), 1);

        if(itemStack.getItem()instanceof BlockItem)
        {
            poseStack.translate(0.33, 0.6, 0.33);//{[0.5,0,0] ,[0,0,1],[0,-0.5,0]}
        }
        else
        {
            poseStack.translate(0.33, 0.7, 0.33);//{[0.5,0,0] ,[0,0,1],[0,-0.5,0]}
        }

        BakedModel bakedModel = itemRenderer.getModel(itemStack, blockEntity.getLevel(), null, 0);
        itemRenderer.render(itemStack, ItemDisplayContext.GROUND, true, poseStack, buffer,
                LightTexture.FULL_BRIGHT, packedOverlay, bakedModel);
        poseStack.popPose();//{[1,0,0],[0,1,0],[0,0,1]},[0,0,1]->[0.75,1.2,0.5]





        poseStack.pushPose();
//        poseStack.translate(0.75,1.2,0.5);

        applyBlockStateRotation(blockEntity.getBlockState(), poseStack);//{[1,0,0][0,1,0][0,0,1]}[0,0,0]->[0.5,1.2,0.25]


        poseStack.mulPose(new Quaternionf().rotateY((float) Math.PI/2));//{[0,0,-1][0,1,0][1,0,0]}[0,0,0]
        poseStack.translate(-0.25,1.2,0.5);//{[0,0,-1][0,1,0][1,0,0]}[0.5,1.2,0.25]
        BakedModel bakedModel2 = itemRenderer.getModel(new ItemStack(ModItems.STORE_TAG.get(),1), blockEntity.getLevel(), null, 0);
        itemRenderer.render(itemStack, ItemDisplayContext.GROUND, true, poseStack, buffer,
                LightTexture.FULL_BRIGHT, packedOverlay, bakedModel2);


        poseStack.popPose();
    }
    private void applyBlockStateRotation(BlockState state, PoseStack poseStack) {
        // 确保方块有方向属性
        if (state.hasProperty(BlockStateProperties.FACING)) {
            Direction facing = state.getValue(BlockStateProperties.FACING);

            // 应用旋转
            poseStack.translate(0.5, 0.5, 0.5);
            switch (facing) {
                case EAST:
                    poseStack.mulPose(Axis.YP.rotationDegrees(270));
                    break;
                case SOUTH:
                    poseStack.mulPose(Axis.YP.rotationDegrees(180));
                    break;
                case WEST:
                    poseStack.mulPose(Axis.YP.rotationDegrees(90));
                    break;
                case UP:
                    poseStack.mulPose(Axis.XP.rotationDegrees(90));
                    break;
                case DOWN:
                    poseStack.mulPose(Axis.XP.rotationDegrees(-90));
                    break;
                // NORTH 不需要旋转
            }
            poseStack.translate(-0.5, -0.5, -0.5);
        }
    }

    private void renderHighLight(StoreBlockEntity blockEntity, float partialTick,
                                 PoseStack poseStack, MultiBufferSource buffer,
                                 int packedLight, int packedOverlay) {
        Minecraft mc = Minecraft.getInstance();

        // Rewrite this to use shader that does outline instead

        Camera activeRenderInfo = mc.getEntityRenderDispatcher().camera;
        Vec3 projectedView = activeRenderInfo.getPosition();
        BlockPos blockPos=blockEntity.getBlockPos();

        poseStack.pushPose();
        poseStack.clear();
        poseStack.translate(blockPos.getX() - projectedView.x, blockPos.getY() - projectedView.y, blockPos.getZ() - projectedView.z);
//        poseStack.translate(1,1,1);
        poseStack.scale(2f,2f,2f);

//        Vec3 viewVector = activeRenderInfo.getLookVector().scale(-depthOffset);
//        poseStack.translate(viewVector.x, viewVector.y, viewVector.z);

        Matrix4f matrix = poseStack.last().pose();
        AABB aabb = new AABB(0, 0, 0, 1, 1.5, 1).inflate(0.001);// 略大于方块避免Z-fighting


        VertexConsumer glowConsumer = buffer.getBuffer(GlowRenderType.LINES_NORMAL);
        renderLineBox(glowConsumer, matrix, aabb, 255, 255, 255, 255);

        mc.renderBuffers().bufferSource().endBatch(GlowRenderType.LINES_NORMAL);
        poseStack.popPose();
    }


    private void renderLineBox(VertexConsumer consumer, Matrix4f matrix, AABB aabb,
                               int r, int g, int b, int a) {
        float minX = (float)aabb.minX;
        float minY = (float)aabb.minY;
        float minZ = (float)aabb.minZ;
        float maxX = (float)aabb.maxX;
        float maxY = (float)aabb.maxY;
        float maxZ = (float)aabb.maxZ;

        // 底面
        line(consumer, matrix, minX, minY, minZ, maxX, minY, minZ, r, g, b, a);
        line(consumer, matrix, maxX, minY, minZ, maxX, minY, maxZ, r, g, b, a);
        line(consumer, matrix, maxX, minY, maxZ, minX, minY, maxZ, r, g, b, a);
        line(consumer, matrix, minX, minY, maxZ, minX, minY, minZ, r, g, b, a);

        // 顶面
        line(consumer, matrix, minX, maxY, minZ, maxX, maxY, minZ, r, g, b, a);
        line(consumer, matrix, maxX, maxY, minZ, maxX, maxY, maxZ, r, g, b, a);
        line(consumer, matrix, maxX, maxY, maxZ, minX, maxY, maxZ, r, g, b, a);
        line(consumer, matrix, minX, maxY, maxZ, minX, maxY, minZ, r, g, b, a);

        // 侧面
        line(consumer, matrix, minX, minY, minZ, minX, maxY, minZ, r, g, b, a);
        line(consumer, matrix, maxX, minY, minZ, maxX, maxY, minZ, r, g, b, a);
        line(consumer, matrix, maxX, minY, maxZ, maxX, maxY, maxZ, r, g, b, a);
        line(consumer, matrix, minX, minY, maxZ, minX, maxY, maxZ, r, g, b, a);
    }

    // 绘制单条线段
    private void line(VertexConsumer consumer, Matrix4f matrix,
                      float x1, float y1, float z1,
                      float x2, float y2, float z2,
                      int r, int g, int b, int a) {
        consumer.vertex(matrix, x1, y1, z1).color(r, g, b, a).endVertex();
        consumer.vertex(matrix, x2, y2, z2).color(r, g, b, a).endVertex();
    }
}